import cv2

def move_check(front_mat, after_mat):
    front_gray = cv2.cvtColor(front_mat, cv2.COLOR_BGR2GRAY)
    after_gray = cv2.cvtColor(after_mat, cv2.COLOR_BGR2GRAY)

    diff_gray = cv2.absdiff(front_gray, after_gray)
    _, diff_gray = cv2.threshold(diff_gray, 25, 255, cv2.THRESH_BINARY)

    element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    diff_gray = cv2.erode(diff_gray, element)

    element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20))
    diff_gray = cv2.dilate(diff_gray, element2)

    contours, _ = cv2.findContours(diff_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    resframe = after_mat.copy()
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(resframe, (x, y), (x + w, y + h), (0, 255, 0), 4)

    return resframe, contours

cap = cv2.VideoCapture("output2.avi")
count = 0
tempframe = None
while True:
    ret, frame = cap.read()
    if not ret:
        break

    if count == 0:
        res, contours = move_check(frame, frame)
        tempframe = frame.copy()
    else:
        res, contours = move_check(tempframe, frame)
        tempframe = frame.copy()

    #cv2.imshow("frame", frame)
    cv2.imshow("res", res)
    print(f"Detected {len(contours)} boxes in the frame.")  # 打印检测到的框框数量
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

    count += 1

cap.release()
cv2.destroyAllWindows()